package com.dmwork.service.work.controller.front.me;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmwork.common.base.result.R;
import com.dmwork.common.base.util.JwtInfo;
import com.dmwork.common.base.util.JwtUtils;
import com.dmwork.service.base.properties.RedisTimeoutProperties;
import com.dmwork.service.work.entity.Work;
import com.dmwork.service.work.entity.WorkDescription;
import com.dmwork.service.work.entity.WorkPictureInfo;
import com.dmwork.service.work.entity.WorkType;
import com.dmwork.service.work.entity.vo.WorkBaseInfoVo;
import com.dmwork.service.work.entity.vo.WorkDetailInfoVo;
import com.dmwork.service.work.entity.vo.WorkPublishInfoVo;
import com.dmwork.service.work.entity.vo.WorkUpdateInfoVo;
import com.dmwork.service.work.feign.OssFileFeignService;
import com.dmwork.service.work.feign.WorkCollectFeignService;
import com.dmwork.service.work.mq.sender.MessageSender;
import com.dmwork.service.work.service.*;
import com.google.gson.Gson;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisKeyValueAdapter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 李天
 * @since 2021-03-14
 */
@Slf4j
@Api(description = "个人作品管理")
@Transactional
@RestController
@RequestMapping("/front/dm_work/work/me")
public class FrontMeWorkController {

    @Autowired
    private WorkService workService;
    @Autowired
    private WorkTypeService workTypeService;
    @Autowired
    private WorkCollectFeignService workCollectFeignService;
    @Autowired
    private MessageSender messageSender;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisTimeoutProperties redisTimeoutProperties;

    private final String TEMP_STORAGE_WORK_KEY = "temp_storage_work";

    @ApiOperation("发布作品")
    @PostMapping("publish_work")
    public R publishWork(HttpServletRequest request,
                         @ApiParam(value = "作品投稿信息")
                         @RequestBody WorkPublishInfoVo workPublishInfoVo) {
        //获取用户id
        JwtInfo jwtToken = JwtUtils.getCustomerInfoByJwtToken(request);
        String id = jwtToken.getId();

        //转换作品中标题和简介的Emoji
        workPublishInfoVo.setTitle(EmojiParser.parseToAliases(workPublishInfoVo.getTitle()));
        workPublishInfoVo.setDescription(EmojiParser.parseToAliases(workPublishInfoVo.getDescription()));
        String workId = workService.publishWork(id, workPublishInfoVo);
        //向动态功能所在模块发送新作品投稿消息
        HashMap<String, Object> messageMap = new HashMap<>();
        messageMap.put("customerId", id);
        messageMap.put("workId", workId);
        messageMap.put("content", workPublishInfoVo.getFeedWord());
        messageSender.sendWorkPublishMessage(messageMap, new HashMap<>());

        //删除redis缓存中该用户的投稿草稿
        redisTemplate.delete(TEMP_STORAGE_WORK_KEY+jwtToken.getId());

        return R.ok().message("保存成功");
    }

    @ApiOperation("保存个人作品发布的草稿")
    @PostMapping("temp_storage_work")
    public R tempStorageWork(HttpServletRequest request, @ApiParam(value = "作品投稿信息") @RequestBody WorkPublishInfoVo workPublishInfoVo) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        redisTemplate.opsForValue().set(TEMP_STORAGE_WORK_KEY+jwtInfo.getId(), workPublishInfoVo, redisTimeoutProperties.getTempStorageWork(), TimeUnit.DAYS);
        return R.ok().message("暂存成功");
    }

    @ApiOperation("获取个人作品的发布草稿")
    @GetMapping("get_temp_storage_work")
    public R getTempStorageWork(HttpServletRequest request) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        if (!redisTemplate.hasKey(TEMP_STORAGE_WORK_KEY+jwtInfo.getId())) {
            return R.ok().message("无草稿");
        } else {
            WorkPublishInfoVo workPublishInfoVo = (WorkPublishInfoVo) redisTemplate.opsForValue().get(TEMP_STORAGE_WORK_KEY+jwtInfo.getId());
            return R.ok().data("item", workPublishInfoVo);
        }
    }

    @ApiOperation("删除此次的作品发布草稿")
    @DeleteMapping("remove_temp_storage_work")
    public R removeTempStorageWork(HttpServletRequest request) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        redisTemplate.delete(TEMP_STORAGE_WORK_KEY+jwtInfo.getId());
        log.info("草稿被删除");
        return R.ok().message("删除成功");
    }


    @ApiOperation("获取个人作品详情")
    @GetMapping("get_info/{workId}")
    public R getInfo(HttpServletRequest request, @ApiParam(value = "workId", required = true) @PathVariable("workId") String workId) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        WorkDetailInfoVo workDetailInfoVo = workService.getWorkDetailInfoById(workId);
        workDetailInfoVo.setCustomerName(jwtInfo.getName());
        //转换作品中标题和简介的Emoji
        workDetailInfoVo.setTitle(EmojiParser.parseToUnicode(workDetailInfoVo.getTitle()));
        workDetailInfoVo.setDescription(EmojiParser.parseToUnicode(workDetailInfoVo.getDescription()));
        return R.ok().data("item", workDetailInfoVo);
    }


    @ApiOperation("修改个人作品信息")
    @PutMapping("update_work")
    public R updateWork(@RequestBody WorkUpdateInfoVo workUpdateInfoVo) {
        // 更新个人作品信息
        workService.updateWorkInfo(workUpdateInfoVo);
        return R.ok().message("修改成功");
    }


    @ApiOperation("获取个人作品列表")
    @GetMapping("get_info_list/{page}/{limit}")
    public R getInfoList(
            HttpServletRequest request,
            @ApiParam(value = "页数", required = true) @PathVariable("page") Integer page,
            @ApiParam(value = "每页记录数", required = true) @PathVariable("limit") Integer limit) {

        log.error(request.toString());

        JwtInfo jwtToken = JwtUtils.getCustomerInfoByJwtToken(request);
        String id = jwtToken.getId();
        Page<Work> workPage = workService.getInfoPage(id, page, limit);
        if (workPage.getTotal() == 0) {
            return R.ok().message("暂无数据").data("total", 0);
        } else {
            List<WorkBaseInfoVo> workBaseInfoVoList=new ArrayList<>();
            //获取作品id列表
            List<String> workIdList=new ArrayList<>(workPage.getRecords().size());
            for (Work work : workPage.getRecords()) {
                workIdList.add(work.getId());
            }

            List<WorkType> workTypeList = workTypeService.list();

            Map<String, Integer> collectCountMap = workCollectFeignService.getBatchCollectCountByWorkIdList(workIdList);

            for (Work work : workPage.getRecords()) {
                WorkBaseInfoVo workBaseInfoVo = new WorkBaseInfoVo();
                //转换作品中标题的Emoji
                work.setTitle(EmojiParser.parseToAliases(work.getTitle()));
                workBaseInfoVo.setCollectCount(collectCountMap.get(work.getId()));
                BeanUtils.copyProperties(work, workBaseInfoVo);
                for (WorkType workType : workTypeList) {
                    if (workType.getId().equals(work.getTypeId())) {
                        workBaseInfoVo.setTypeName(workType.getName());
                        break;
                    }
                }
                workBaseInfoVoList.add(workBaseInfoVo);
            }
            return R.ok().data("total", workPage.getTotal()).data("rows", workBaseInfoVoList);
        }
    }

    @ApiOperation("删除个人作品")
    @DeleteMapping("remove_work/{workId}")
    public R removeWork(@ApiParam(value = "作品id", required = true) @PathVariable("workId") String workId) {
        workService.removeWork(workId);
        return R.ok().message("删除成功");
    }


}

